package utils;

import java.awt.Graphics;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.RescaleOp;
import java.awt.image.ShortLookupTable;

public class ImageOperationUtils {

	/**
	 * do a rescaleOp
	 * 
	 * @param source
	 *            : img src
	 * @param contrastValue
	 * @param brightnessValue
	 * @return
	 */
	public static BufferedImage createRescaleOp(BufferedImage source,
			float contrastValue, float brightnessValue) {
		float[] scales = { contrastValue / 100, contrastValue / 100,
				contrastValue / 100, 1.0f };
		float[] offsets = { brightnessValue, brightnessValue, brightnessValue,
				0f };

		RescaleOp op = new RescaleOp(scales, offsets, null);
		return op.filter(source, null);
	}

	/**
	 * create an image from source with the opacity value
	 * 
	 * @param source
	 * @param opacity
	 *            : opacity ( 0 - 255 )
	 * @return
	 */
	public static BufferedImage createOpacityOp(BufferedImage source, int alpha) {
		float[] scales = { 1.0f, 1.0f, 1.0f, 1.0f };
		float[] offsets = { 0f, 0f, 0f, (float) alpha };

		RescaleOp op = new RescaleOp(scales, offsets, null);
		return op.filter(source, null);
	}

	public static BufferedImage createConvolveOp(BufferedImage source,
			float[] matrix) {
		Kernel kernel = new Kernel(3, 3, matrix);
		ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
				null);
		return convolve.filter(source, null);
	}

	public static BufferedImage createLookupOp(BufferedImage source,
			short[][] colorChange) {
		LookupOp lookupOp = new LookupOp(new ShortLookupTable(0, colorChange),
				null);
		return lookupOp.filter(source, null);
	}
	
	public static BufferedImage createBlackAndWhite(BufferedImage source){
		 ColorSpace     grayScale       = ColorSpace.getInstance(ColorSpace.CS_GRAY);
         ColorConvertOp colorConvert    = new ColorConvertOp(grayScale, null);
         BufferedImage imgDest = colorConvert.filter(source, null);
         BufferedImage imgReturn = new BufferedImage(imgDest.getWidth(), imgDest.getHeight(), BufferedImage.TYPE_INT_ARGB);
         Graphics g = imgReturn.getGraphics();
         g.drawImage(imgDest, 0, 0, null);
         g.dispose();
         
         return imgReturn;
	}

}
